package com.ruizhong.centercontroll.util;




import com.ruizhong.centercontroll.MainActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ControllThread implements Runnable {

    private String aimIp;

    private Socket socket;

    private InputStream is;

    private OutputStream os;

    private ObjectOutputStream oos;

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    private MainActivity mainActivity;

    private Boolean Running = true;

    public ControllThread(String aimIp, MainActivity mainActivity) {
        this.aimIp = aimIp;
        this.mainActivity = mainActivity;

    }

    @Override
    public void run() {
        try {
            socket = new Socket(aimIp, 8088);
            is = socket.getInputStream();
            os = socket.getOutputStream();
            oos = new ObjectOutputStream(os);
            while (Running) {
                Thread.sleep(5000);
            }
        } catch (IOException e) {
            e.printStackTrace();
            try {
                if (socket != null) {
                    socket.close();
                }

                mainActivity.goBack();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            try {
                if (socket != null) {
                    socket.close();
                }

                mainActivity.goBack();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void sendEvent(final KeyInfo event) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    if (event.getType().equals("word")) {
                        if (!event.getWord().equals("")) {
                            oos.writeObject(event);
                        }
                    } else {

                        oos.writeObject(event);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void stopController(){
        Running = false;
    }

}
